package com.loe.ui.quickjs

import android.webkit.JavascriptInterface
import com.loe.mvp.ext_java.safe
import com.loe.ui.jsContext
import com.loe.ui.key
import com.loe.ui.registerFun
import com.quickjs.JSArray
import com.quickjs.JSContext
import com.quickjs.JSFunction
import com.quickjs.JSObject

/** 选择器 */
fun JSContext.initSelector() = registerClass({ thisObj, args ->

    var onItemSelect: JSFunction? = null
    if (args.length() > 0)
    {
        onItemSelect = args.get(0) as JSFunction
    }

    val list = ArrayList<JSObject>()

    var selectO: JSObject? = null
    var index: Int? = null

    thisObj.appendJavascriptInterface(object
    {
        @JavascriptInterface
        fun add(o: JSObject)
        {
            list.add(o)
        }

        @JavascriptInterface
        fun setOnItemSelect(on: JSFunction)
        {
            onItemSelect = on
        }

        @JavascriptInterface
        fun getSelect(): JSObject?
        {
            return selectO
        }

        @JavascriptInterface
        fun getIndex(): Int?
        {
            return index
        }
    })

    fun select(o: JSObject)
    {
        if (selectO.key == o.key) return
        list.forEachIndexed()
        { i, it ->
            if (it.key == o.key)
            {
                selectO = o
                index = i
                safe { onItemSelect?.call(thisObj, JSArray(context).push(it).push(true)) }
            } else
            {
                safe { onItemSelect?.call(thisObj, JSArray(context).push(it).push(false)) }
            }
        }
    }

    thisObj.registerFun("select")
    {
        val p = it.get(0)
        if (p is JSObject)
        {
            select(p)
        } else
        {
            select(list[p as Int])
        }
    }
}, "Selector")